#!/usr/local/bin/ruby
# $Id$
# Ruby version of Y! dictionary, derived from leeym's perl script
# Author: Cheng-Lung Sung <clsung@FreeBSD.org>
# Version: 0.9
# Date: 2007/01/12
require 'term/ansicolor'
require 'net/http'
require 'iconv'

def ydict (shift)
    raise ArgumentError, 'Must specify word' if shift == nil
    include Term::ANSIColor
    Net::HTTP.start('tw.dictionary.yahoo.com', 80) {|http|
	response = http.get('/search?p=' + shift)
	@html = response.body.to_s
    }
    i = 0
    html = @html.to_s.gsub /\r/, ""
    html = html.gsub /\n/, ""
    if html =~ /<em class="warning">/
	if html =~ /<em class="warning">.*?>(\S+)<.*?<\/em>/
	    q = $1;
	    print bold , yellow , "\nERROR: ", shift , " -> " , q , "\n",  reset
	    return ydict(q)
	else
	    print bold , yellow , "ERROR: ", shift , "\n",  reset
	    return
	end
    end
    print bold , yellow , "\n" + shift + "\n" , reset
    while html =~ /<div class=p(\w+)>(.*?)<\/div>/i
	type = $1
	line = $2
	html = $'
	$reset = reset
	line = line.gsub /^\s+/, ""
	line = line.gsub /\s+$/, ""
	if type == 'cixin'
	    i = 0
	    $color = bold, red
	elsif type == 'chi' or type == 'eng'
	    $color = cyan;
	    $reset = reset  + $color
	    line = "\t" + line
	elsif type == 'explain'
	    i = i + 1
	    line = i.to_s + " " + line
	else 
	    color = bold, blue
	    next
	end
	line = line.gsub /<b>/, bold
	line = line.gsub /<\/b>/, $reset
	line = line.gsub /<[^>]+>/, $reset
	if ENV['LC_CTYPE'] =~ /big5/i 
	    line = Iconv.new('big5-hkscs', 'utf-8').iconv(line)
	end
	print $color , line + "\n" , reset
    end
    puts ""
end

ydict(ARGV[0])
